<template>
  <div>
    <el-form
      ref="form"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="auto"
      label-suffix="："
    >
      <el-form-item :label="$t('message.dbhb')" class="select-style" prop="picUrl" :rules="{ required: true, message: param.code == 'coinsZero' ? $t('message.qsc') + $t('message.hb'):$t('message.qxz') + $t('message.hb'), trigger: 'change' }">
        <el-radio-group v-model="param.code" @change="changeType">
          <el-radio v-for="(item, index) in memberImgList" :key="index" :label="item.code">{{ item.remaks }}</el-radio>
        </el-radio-group>
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="COIN_IMG"
            :fixed-number="[100,100]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <div class="upload-wrap">
          <el-upload
            v-if="param.code == 'coinsZero'"
            class="device-uploader"
            :action="uploadFileUrl"
            :data="uploadParam"
            :show-file-list="false"
            accept=".jpg,.png,.jpeg"
            :auto-upload="false"
            :on-change="addFileChange"
          >
            <img
              style="width: 84px; height: 84px"
              src="@/assets/images/btn_uploadcard.png"
              alt=""
            >
            <div
              v-show="param.picUrl"
              class="file"
              :style="'background-image: url(' + param.picUrl + ')'"
            >
              <div class="delete">
                <i class="el-icon-delete icon" @click.stop="deleteImage" />
              </div>
            </div>
          </el-upload>
        </div>
        <el-image
          v-if="param.code != 'coinsZero' && param.picUrl"
          style="width: 84px; height: 84px"
          :src="param.picUrl"
          :preview-src-list="[param.picUrl]"
        />
      </el-form-item>
      <el-form-item :label="$t('message.zklx')" class="select-style" prop="discountType">
        <el-select
          v-model="param.discountType"
          :placeholder="$t('message.qxz') + $t('message.zklx')"
          class="w200"
        >
          <el-option
            v-for="item in discountTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <div
        v-if="param.discountType == '1'"
        style="display: flex; flex-wrap: wrap"
      >
        <el-form-item
          v-for="vip in vipTypes"
          :key="vip.id"
          label-width="auto"
          style="width: 50%"
          align="center"
          :label="vip.name"
          :prop="`discountMap.${vip.cardId}`"
          :rules="{
            required: true,
            message: $t('message.qsr') + $t('message.hyzk'),
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="param.discountMap[vip.cardId]"
            onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            oninput="if(value<0||value>1) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
            type="text"
            :placeholder="$t('message.qsr') + $t('message.hyzk') + '(' + $t('message.bllwxs') + ')'"
            maxlength="50"
          />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button v-if="meta.indexOf('CoinsOtherUpdate') > -1" type="primary" :loading="subLoading" @click="onSubmit">{{ $t('message.tj') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Cropper from '@/components/cropper'
import { cardList, uploadFile, coinsGoodsPicList, coinsGoodsOtherInfo, coinsGoodsOtherUpdate } from '@/api'
export default {
  components: {
    Cropper
  },
  props: {
    meta: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      param: {
        discountMap: {},
        discountType: '0'
      },
      rules: {},
      subLoading: false,

      vipTypes: [],
      discountTypeList: [
        { value: '0', label: this.$t('message.mrzk') },
        { value: '1', label: this.$t('message.zdyzk') }
      ],

      optionImg: '',
      memberImgList: [],
      fileinfo: {},
      dialogCropperVisible: false,
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'COIN_IMG'
      }
    }
  },
  created() {
    this.getMrMemberImg()
    // this.getCardList()
  },
  methods: {
    getCardList() {
      // 获取卡类型列表
      cardList({
        pagination: {
          page: 1,
          rows: 1000
          // firstQueryTime: this.firstQueryTime
        }
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            res.recordList.forEach((item) => {
              if (item.status === '1') {
                this.vipTypes.push({
                  name: item.cardName,
                  id: item.id,
                  value: null
                })
              }
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    getGoodsDetailInfo() {
      // 获取卡类型列表
      coinsGoodsOtherInfo({
        param: {}
      })
        .then((res) => {
          this.vipTypes = res.record.discountList
          this.param = res.record
          if (res.record.picUrl) {
            const index = this.memberImgList.map(i => i.showPic).indexOf(res.record.picUrl)
            if (index === -1) {
              this.$set(this.param, 'code', 'coinsZero')
            } else {
              this.$set(this.param, 'code', this.memberImgList[index].code)
            }
          } else {
            this.$set(this.param, 'picUrl', this.memberImgList[0].showPic)
            this.$set(this.param, 'code', this.memberImgList[0].code)
          }

          if (res.record.discountType === '0') {
            this.$set(this.param, 'discountMap', {})
          } else {
            const discountmap = {}
            res.record.discountList.forEach(item => {
              discountmap[item.cardId] = item.val
            })
            this.$set(this.param, 'discountMap', discountmap)
          }
        })
    },
    // 默认卡样式
    getMrMemberImg() {
      coinsGoodsPicList({ param: { type: 5 }}).then(res => {
        if (res.errorCode === '000000') {
          this.memberImgList = res.recordList || []
          this.getGoodsDetailInfo()
        }
      })
    },
    onSubmit() {
      const { param } = this
      param.isNormal = this.param.code === 'coinsZero' ? '0' : '1'
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.param.discountType === '1') {
            // const temp = Object.keys(param.discountMap)
            param.discountList = this.vipTypes.map(item => {
              const obj = {}
              obj.cardId = item.cardId
              obj.name = item.name
              obj.val = param.discountMap[item.cardId]
              // this.vipTypes.forEach(item2 => {
              //   if (item === item2.id) {
              //     obj.name = item2.name
              //   }
              // })
              return obj
            })
          }
          this.subLoading = true
          coinsGoodsOtherUpdate({ param }).then(res => {
            this.subLoading = false
            if (res.errorCode !== '000000') return
            this.$message.success(this.$t('message.xgcg'))
            this.getMrMemberImg()
          }, () => {
            this.subLoading = false
          })
        }
      })
    },
    changeType(e) {
      if (e === 'coinsZero') {
        this.$set(this.param, 'pic', '')
        this.$set(this.param, 'picUrl', '')
      } else {
        const arr = this.memberImgList
        arr.forEach(s => {
          if (s.code === e) {
            this.$set(this.param, 'pic', s.pic)
            this.$set(this.param, 'picUrl', s.showPic)
          }
        })
      }
      this.$refs.form.clearValidate()
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'picUrl', config.showUrl)
        this.$set(this.param, 'pic', config.insertUrl)
        this.dialogCropperVisible = false
        this.$refs.form.clearValidate()
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      // this.files = file.raw;
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除头像
    deleteImage() {
      this.$set(this.param, 'pic', '')
      this.$set(this.param, 'picUrl', '')
    }
  }
}
</script>

<style lang="scss" scoped>
 @import "@/styles/variables.scss";
.device-uploader {
  width: 84px;
  height: 84px;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>
